const grpc = require("@grpc/grpc-js")
const message_proto = require("./proto")
const { Errors, code_prefix } = require("./const")
const {v4:uuidv4} = require("uuid")
const { email_user } = require("./config")
const { SendMail } = require("./email")
const redis_module = require('./redis')

async function GetVarifyCode(GetVarifyReq,GetVarifyRsp) {
    console.log("email:",GetVarifyReq.request.email)
    try{
        let requery_res = await redis_module.GetRedis(code_prefix+GetVarifyReq.request.email);
        console.log(code_prefix+GetVarifyReq.request.email);
        console.log("requery_res:",requery_res);
        let uniqueId = requery_res;
        if(uniqueId ==null)
        {
            uniqueId = uuidv4();
            if(uniqueId.length>4)
            {
                uniqueId = uniqueId.substring(0,4);
            }
            let bres = await redis_module.SetRedisExpire(code_prefix+GetVarifyReq.request.email,uniqueId,600);
            if(!bres)
            {
                GetVarifyRsp(null,{email:GetVarifyReq.request.email,
                    error:Errors.RedisErr
                });
                return;
            }
        }
        
        console.log("uniqueId:",uniqueId)
        let text_str  = "验证码为:"+uniqueId+" 请于十分钟内完成注册"

        //发送邮件
        let _mailOptions = {
            from: email_user,
            to: GetVarifyReq.request.email,
            subject: '验证码',
            text: text_str
        };

        let send_res = await SendMail(_mailOptions);
      

        if(!send_res)
        {
            GetVarifyRsp(null,{email:GetVarifyReq.request.email,
                error:Errors.Exception
            });
            return;
        }
        console.log("Send res:",send_res)
        GetVarifyRsp(null,{email:GetVarifyReq.request.email,
            error:Errors.Success
        });

    }catch(error){
        console.log("catch error:",error)
        GetVarifyRsp(null,{ email:GetVarifyReq.request.email,
            error:Errors.Exception
        });
    }
    
}

function main(){
    var server = new grpc.Server()
    server.addService(message_proto.VarifyService.service,{GetVarifyCode:GetVarifyCode})
    server.bindAsync('0.0.0.0:50051',grpc.ServerCredentials.createInsecure(),()=>{
        //server.start()
        console.log('grpc server start')
    })
}

main()